package com.epi.two.socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.*;

/**
 * @author dxy
 * @version 1.0
 */
public class ClientDemo {
    public static void main(String[] args) {
        try (Socket socket = new Socket("127.0.0.1", 8888);
             var in = new Scanner(socket.getInputStream());
             var userIn = new Scanner(System.in);
             var out = new PrintWriter(socket.getOutputStream(), true)) {

            // 接收服务器的问候
            if (in.hasNextLine()) {
                System.out.println(in.nextLine());
            }

            while (true) {
                System.out.print("【Request】");
                String userInput = userIn.nextLine();
                out.println(userInput);

                if ("BYE".equalsIgnoreCase(userInput)) {
                    // 发完 BYE 就半关闭“写通道”，表示不再发送
                    socket.shutdownOutput();
                }

                String response = in.nextLine();
                System.out.println("【Response】"+response);
                if ("Bye~".equals(response)) break;
            }


        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
